package vn.orderonline.com.core.business.common;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import vn.orderonline.com.core.business.dto.DistrictDto;
import vn.orderonline.com.core.business.dto.RestResponseDto;
import vn.orderonline.com.core.business.dto.ReturnCode;
import vn.orderonline.core.dao.CityDao;
import vn.orderonline.core.dao.DistrictDao;
import vn.orderonline.core.dao.entity.City;

@Service
@Transactional
public class CommonImpl implements ICommon {

	@Autowired
	private CityDao cityDao;
	@Autowired
	private DistrictDao districtDao;

	@Override
	public RestResponseDto getAllCity() {
		Map<String, String> map = new LinkedHashMap<>();
		List<City> cityList = cityDao.findAll();
		if (!cityList.isEmpty()) {
			for (City city : cityList) {
				map.put(city.getCityId().toString(), city.getCityName());
			}
		}
		return new RestResponseDto(ReturnCode.SUCCESS, map);
	}

	@Override
	public String getCityNameByCityId(Integer cityId) {
		if (cityId != null) {
			return cityDao.getCityNameByCityId(cityId);
		}
		return null;
	}

	@Override
	public Map<String, String> getDistrictByCityId(Integer cityId) {
		Map<String, String> map = new LinkedHashMap<>();
		List<Object[]> list = districtDao.getAllDistrictByCityId(cityId);
		if (!list.isEmpty()) {
			for (Object[] obj : list) {
				map.put(obj[0].toString(), obj[1].toString());
			}
		}
		return map;
	}

	@Override
	public Map<String, String> cityList() {
		Map<String, String> map = new LinkedHashMap<>();
		List<City> cityList = cityDao.findAll();
		if (!cityList.isEmpty()) {
			for (City city : cityList) {
				map.put(city.getCityId().toString(), city.getCityName());
			}
		}
		return map;
	}

	@Override
	public List<DistrictDto> districtList(Integer cityId) {
		List<DistrictDto> list = new ArrayList<>();
		List<Object[]> objList = districtDao.getAllDistrictByCityId(cityId);
		if (!objList.isEmpty()) {
			DistrictDto dto = null;
			for (Object[] obj : objList) {
				dto = new DistrictDto();
				dto.setDistrictId((Integer) obj[0]);
				dto.setDistrictName((String) obj[1]);
				list.add(dto);
			}
		}
		return list;
	}

	@Override
	public Map<String, String> districMap(Integer cityId) {
		Map<String, String> map = new LinkedHashMap<>();
		List<Object[]> list = districtDao.getAllDistrictByCityId(cityId);
		if (!list.isEmpty()) {
			for (Object[] obj : list) {
				map.put(obj[0].toString(), obj[1].toString());
			}
		}
		return map;
	}

	@Override
	public String getDistrictNameByDistrictId(Integer districtId) {
		if (districtId != null) {
			return districtDao.getDistrictNameByDistrictId(districtId);
		}
		return null;
	}
}
